import { DIContainer } from '../infrastructure/di';
import { ServiceLayerUnification } from './ServiceLayerUnification';

/**
 * 统一服务初始化器
 * 在项目启动时集成新的服务层架构
 */
export class UnifiedServiceInitializer {
    private static unification: ServiceLayerUnification;
    private static isEnabled = false;

    /**
     * 初始化统一服务层
     * 在项目启动时调用
     */
    static async initialize(container: DIContainer, enabled: boolean = true): Promise<void> {
        if (!enabled) {
            console.log('🔧 Unified service layer is disabled');
            return;
        }

        console.log('🚀 Initializing Unified Service Layer...');
        
        try {
            // 创建服务层统一实例
            this.unification = new ServiceLayerUnification(container);
            
            // 开始统一重构
            await this.unification.startUnification();
            
            this.isEnabled = true;
            console.log('✅ Unified Service Layer initialized successfully');
            
            // 设置优雅关闭
            this.setupGracefulShutdown();
            
        } catch (error) {
            console.error('❌ Failed to initialize Unified Service Layer:', error);
            // 不抛出错误，允许项目继续使用旧服务
            console.log('🔄 Falling back to legacy service layer');
        }
    }

    /**
     * 获取统一服务实例
     */
    static getUnification(): ServiceLayerUnification | null {
        return this.isEnabled ? this.unification : null;
    }

    /**
     * 检查是否启用了统一服务层
     */
    static isUnifiedServiceEnabled(): boolean {
        return this.isEnabled;
    }

    /**
     * 手动推进迁移（用于测试和运维）
     */
    static async advanceMigration(serviceName: string, trafficPercentage?: number): Promise<void> {
        if (!this.isEnabled || !this.unification) {
            throw new Error('Unified service layer is not enabled');
        }
        
        await this.unification.advanceMigration(serviceName, trafficPercentage);
    }

    /**
     * 手动回滚迁移（用于紧急情况）
     */
    static async rollbackMigration(serviceName: string, reason: string): Promise<void> {
        if (!this.isEnabled || !this.unification) {
            throw new Error('Unified service layer is not enabled');
        }
        
        await this.unification.rollbackMigration(serviceName, reason);
    }

    /**
     * 获取迁移状态
     */
    static getMigrationStatus(serviceName?: string) {
        if (!this.isEnabled || !this.unification) {
            return null;
        }
        
        return this.unification.getMigrationStatus(serviceName);
    }

    /**
     * 获取服务健康状态
     */
    static async getServiceHealth() {
        if (!this.isEnabled || !this.unification) {
            return null;
        }
        
        return await this.unification.getServiceHealth();
    }

    /**
     * 设置优雅关闭
     */
    private static setupGracefulShutdown(): void {
        const gracefulShutdown = async (signal: string) => {
            console.log(`🔄 Received ${signal}, shutting down unified services gracefully...`);
            
            try {
                if (this.unification) {
                    const registry = this.unification.getUnifiedRegistry();
                    await registry.destroyAll();
                }
                console.log('✅ Unified services shut down successfully');
            } catch (error) {
                console.error('❌ Error during unified services shutdown:', error);
            }
            
            process.exit(0);
        };

        process.on('SIGINT', () => gracefulShutdown('SIGINT'));
        process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    }
}

/**
 * 在core/index.ts中集成的辅助函数
 */
export async function initializeUnifiedServices(container: DIContainer): Promise<void> {
    // 从环境变量或配置中读取是否启用统一服务
    const enableUnifiedServices = process.env.ENABLE_UNIFIED_SERVICES === 'true' || 
                                 process.env.NODE_ENV === 'development';
    
    await UnifiedServiceInitializer.initialize(container, enableUnifiedServices);
}

/**
 * 管理命令工具
 * 可以通过这些方法手动管理迁移过程
 */
export const UnifiedServiceCommands = {
    /**
     * 开始BagService迁移测试
     */
    async startBagServiceTesting(): Promise<void> {
        console.log('🧪 Starting BagService migration testing...');
        await UnifiedServiceInitializer.advanceMigration('BagService', 10); // 10%流量
        console.log('✅ BagService migration testing started (10% traffic)');
    },

    /**
     * 增加BagService迁移流量
     */
    async increaseBagServiceTraffic(percentage: number): Promise<void> {
        console.log(`📈 Increasing BagService traffic to ${percentage}%...`);
        await UnifiedServiceInitializer.advanceMigration('BagService', percentage);
        console.log(`✅ BagService traffic increased to ${percentage}%`);
    },

    /**
     * 完全切换到BagService统一版本
     */
    async switchToBagServiceFully(): Promise<void> {
        console.log('🔄 Switching to BagService unified version fully...');
        await UnifiedServiceInitializer.advanceMigration('BagService', 100);
        console.log('✅ BagService fully switched to unified version');
    },

    /**
     * 紧急回滚BagService
     */
    async emergencyRollbackBagService(reason: string): Promise<void> {
        console.log(`🚨 Emergency rollback of BagService: ${reason}`);
        await UnifiedServiceInitializer.rollbackMigration('BagService', reason);
        console.log('✅ BagService emergency rollback completed');
    },

    /**
     * 获取详细迁移状态
     */
    async getDetailedMigrationStatus(): Promise<void> {
        const status = UnifiedServiceInitializer.getMigrationStatus();
        if (status) {
            console.log('📊 Detailed Migration Status:');
            for (const [serviceName, serviceStatus] of status.entries()) {
                const totalCalls = serviceStatus.successCount + serviceStatus.errorCount;
                const successRate = totalCalls > 0 ? (serviceStatus.successCount / totalCalls * 100).toFixed(2) : '0.00';
                const errorRate = totalCalls > 0 ? (serviceStatus.errorCount / totalCalls * 100).toFixed(2) : '0.00';
                
                console.log(`\n🔍 ${serviceName}:`);
                console.log(`  📊 Phase: ${serviceStatus.config.currentPhase}`);
                console.log(`  📈 Traffic: ${serviceStatus.config.trafficPercentage}%`);
                console.log(`  ✅ Success Rate: ${successRate}%`);
                console.log(`  ❌ Error Rate: ${errorRate}%`);
                console.log(`  ⏱️  Avg Response Time: ${serviceStatus.avgResponseTime.toFixed(2)}ms`);
                console.log(`  📞 Total Calls: ${totalCalls}`);
                
                if (serviceStatus.recentErrors.length > 0) {
                    console.log(`  🚨 Recent Errors: ${serviceStatus.recentErrors.length}`);
                }
            }
        } else {
            console.log('ℹ️ Unified service layer is not enabled');
        }
    },

    /**
     * 获取服务健康状态
     */
    async getServiceHealthStatus(): Promise<void> {
        const health = await UnifiedServiceInitializer.getServiceHealth();
        if (health) {
            console.log('🏥 Service Health Status:');
            for (const [serviceName, healthResult] of health.entries()) {
                const status = healthResult.healthy ? '✅ Healthy' : '❌ Unhealthy';
                console.log(`  ${serviceName}: ${status} - ${healthResult.message}`);
                
                if (healthResult.details) {
                    console.log(`    📊 Response Time: ${healthResult.details.responseTime || 'N/A'}ms`);
                    console.log(`    📈 Error Count: ${healthResult.details.errorCount || 0}`);
                }
            }
        } else {
            console.log('ℹ️ Unified service layer is not enabled');
        }
    }
};

/**
 * 在API或管理界面中暴露的迁移管理接口
 */
export interface MigrationManagementAPI {
    /** 获取迁移状态 */
    getStatus(serviceName?: string): any;
    
    /** 推进迁移 */
    advance(serviceName: string, trafficPercentage?: number): Promise<void>;
    
    /** 回滚迁移 */
    rollback(serviceName: string, reason: string): Promise<void>;
    
    /** 获取健康状态 */
    getHealth(): Promise<any>;
    
    /** 获取迁移报告 */
    getReport(): string;
}

/**
 * 实现迁移管理API
 */
export const migrationAPI: MigrationManagementAPI = {
    getStatus: (serviceName?: string) => {
        return UnifiedServiceInitializer.getMigrationStatus(serviceName);
    },
    
    advance: async (serviceName: string, trafficPercentage?: number) => {
        await UnifiedServiceInitializer.advanceMigration(serviceName, trafficPercentage);
    },
    
    rollback: async (serviceName: string, reason: string) => {
        await UnifiedServiceInitializer.rollbackMigration(serviceName, reason);
    },
    
    getHealth: async () => {
        return await UnifiedServiceInitializer.getServiceHealth();
    },
    
    getReport: () => {
        const unification = UnifiedServiceInitializer.getUnification();
        if (unification) {
            // 获取迁移管理器并生成报告
            const migrationManager = (unification as any).migrationManager;
            return migrationManager?.generateMigrationReport() || 'No migration data available';
        }
        return 'Unified service layer is not enabled';
    }
};
